package com.StarStudio.Controller;

import com.StarStudio.Service.GoodsService;
import com.StarStudio.Service.MinIOFileService;
import com.StarStudio.Utils.QueryPageUtils;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.Entity.*;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.file.FileTypeUtils;
import com.ruoyi.common.core.utils.file.MimeTypeUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/goods")
@Api(tags = "商品接口")
public class GoodsController  {

    @Autowired
    GoodsService goodsService;

    @Autowired
    private MinIOFileService minIOFileService;

    /**
     * 条件查询 商品分页接口
     * @param goods 商品对象
     * @return 分页结果对象 PageResult
     */
    @GetMapping("/page")
    @ApiOperation("商品分页接口 -> 支持条件检索，检索条件封装在优惠券对象Goods中。如需分页，必传pageNum和pageSize")
    public PageResult page(Goods goods){
        QueryPageUtils.startPage();
        PageInfo pageInfo;
        List<Goods> goodsList;
        long allRecordNumber;
        try {
            goodsList = goodsService.findGoodsList(goods);
            allRecordNumber = goodsService.findAllRecordNumber();
            pageInfo = new PageInfo<>(goodsList);
        } catch (Exception e) {
            e.printStackTrace();
            return new PageResult(HttpStatusCode.ERROR, MessageConstant.QUERY_PAGE_FAIL);
        }
        return new PageResult(HttpStatusCode.SUCCESS,MessageConstant.QUERY_PAGE_SUCCESS, pageInfo.getTotal(), goodsList, allRecordNumber);
    }

    /**
     * 移动端商品分页接口
     * @param goods 商品对象
     * @return 分页结果对象
     * @Author ChengLee
     * @Date 2023/05/04
     */
    @GetMapping("/list")
    @ApiOperation("移动端商品分页接口 -> 支持条件检索，检索条件封装在优惠券对象Goods中。如需分页，必传pageNum和pageSize")
    public PageResult mobilePage(Goods goods){
        QueryPageUtils.startPage();
        PageInfo pageInfo;
        List<Goods> goodsList;
        long allRecordNumber;
        try {
            goodsList = goodsService.findGoodsList1(goods);
            allRecordNumber = goodsService.findAllRecordNumber();
            pageInfo = new PageInfo<>(goodsList);
        } catch (Exception e) {
            e.printStackTrace();
            return new PageResult(HttpStatusCode.ERROR, MessageConstant.QUERY_PAGE_FAIL);
        }
        return new PageResult(HttpStatusCode.SUCCESS,MessageConstant.QUERY_PAGE_SUCCESS, pageInfo.getTotal(), goodsList, allRecordNumber);
    }

    /**
     * 获取商品简要信息集合
     * @return 结果对象 Result
     */
    @GetMapping("/choose_info")
    @ApiOperation("获取商品简要信息集合接口 -> 简要信息包括商品ID、商品名称、商品概览图片地址、抢购商品可添加的最大库存")
    public Result getGoodsChooseResultList(){
        List<GoodsChooseResult> goodsChooseResults;
        try {
            goodsChooseResults = goodsService.getGoodsChooseResultList();
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.GET_GOODS_INFO_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.GET_GOODS_INFO_SUCCESS,goodsChooseResults);
    }

    /**
     * 根据商品ID查找商品
     * @param id 商品ID
     * @return 结果对象 Result
     */
    @GetMapping("/{id}")
    @ApiOperation("根据商品ID查找商品接口 -> path必传商品ID")
    public Result findGoodsById(@PathVariable Long id){
        if (id == null){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        Goods byGoodsId;
        try {
             byGoodsId = goodsService.findByGoods_id(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.QUERY_GOODS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.QUERY_GOODS_SUCCESS,byGoodsId);
    }

    /**
     * 根据商品个体ID查询对应商品信息
     * @param goods_item_id 商品个体ID
     * @return 结果对象
     */
    @GetMapping("/by_item_id/{goods_item_id}")
    @ApiOperation("根据商品库存个体ID查询对应商品信息接口 -> path必传商品库存个体ID")
    public Result findGoodsByGoodsItemId(@PathVariable Long goods_item_id){
        if (goods_item_id == null){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        Goods byGoods_item_id;
        try {
            byGoods_item_id = goodsService.findByGoods_Item_Id(goods_item_id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.QUERY_GOODS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.QUERY_GOODS_SUCCESS,byGoods_item_id);
    }

    /**
     * 导出商品信息到 Excel表格
     * @param response http响应
     * @param goods 商品对象
     */
    @Log(title = "商品管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation("商品Excel导出接口 -> 支持条件检索，检索条件封装在商品对象Goods中")
    public void export(HttpServletResponse response, Goods goods) {
        List<Goods> list = goodsService.findGoodsList(goods);
        ExcelUtil<Goods> util = new ExcelUtil<>(Goods.class);
        util.exportExcel(response, list, "商品数据");
    }

    /**
     * 根据商品ID删除商品（可单个删除也可批量删除）
     * @param Ids 删除的商品ID数组
     * @return 结果对象 Result
     */
    @Log(title = "商品管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{Ids}")
    @ApiOperation("根据商品ID删除商品接口 -> 可单个删除也可批量删除，path传商品ID数组")
    public Result deleteGoods(@PathVariable Long[] Ids){
        if (Ids == null || Ids.length == 0){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        try {
            if (Ids.length > 1){
                for (Long id : Ids) {
                    goodsService.DeleteGoodsById(id);
                }
            }else {
                goodsService.DeleteGoodsById(Ids[0]);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.DELETE_GOODS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.DELETE_GOODS_SUCCESS);
    }

    /**
     * 商品概览图片上传
     * @param file 文件对象
     * @return 结果对象 Result
     */
    @Log(title = "商品管理", businessType = BusinessType.IMPORT)
    @PostMapping("/mainPicture")
    @ApiOperation("商品概览图片上传接口 -> 文件名为file")
    public Result mainPicture(MultipartFile file) {
        if (file.isEmpty()){
            return new Result(HttpStatusCode.ERROR, MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        String extension = FileTypeUtils.getExtension(file);
        if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
            return new Result(HttpStatusCode.ERROR,"文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
        }
        Result upload = minIOFileService.upload(new MultipartFile[]{file});
        if (upload == null || upload.getObject() == null) {
            return new Result(HttpStatusCode.ERROR,"文件服务异常，请联系管理员");
        }
        String url = upload.getObject().toString().replace("[","").replace("]","");
        return new Result(HttpStatusCode.SUCCESS, MessageConstant.UPLOAD_IMAGE_SUCCESS, url);
    }

    /**
     * 新增商品
     * @param goods 商品对象
     * @return 结果对象 Result
     */
    @Log(title = "商品管理", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("商品新增接口 -> 商品名称、星级、商品价格（鲜豆）、市场价（人民币）、库存量、兑换截止日期不能为空")
    public Result addGoods(@RequestBody Goods goods){
        if (goods == null || StringUtils.isEmpty(goods.getGoods_name()) || goods.getStar() == null || goods.getGoods_price() == null
            || goods.getMarket_price() == null || goods.getStock() == null || goods.getExchange_deadline() == null){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        try {
            goodsService.addGoods(goods);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.ADD_GOODS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.ADD_GOODS_SUCCESS);
    }

    /**
     * 修改商品
     * @param goods 商品对象
     * @return 结果对象 Result
     */
    @Log(title = "商品管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("商品修改接口 -> 商品ID、商品名称、星级、商品价格（鲜豆）、市场价（人民币）、库存量、兑换截止日期不能为空")
    public Result updateGoods(@RequestBody Goods goods){
        if (goods == null || goods.getGoods_id() == null || StringUtils.isEmpty(goods.getGoods_name()) || goods.getStar() == null
            || goods.getGoods_price() == null || goods.getMarket_price() == null || goods.getStock() == null || goods.getExchange_deadline() == null){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        try {
            goodsService.updateGoods(goods);
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().contains(MessageConstant.REDUCE_STOCK_ACTION_ERROR)){
                return new Result(HttpStatusCode.ERROR,MessageConstant.REDUCE_STOCK_ACTION_ERROR);
            }
            return new Result(HttpStatusCode.ERROR,MessageConstant.UPDATE_GOODS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.UPDATE_GOODS_SUCCESS);
    }
}
